/*
 * TextListEx.java
 *
 * Created on 17 Июнь 2007 г., 21:36
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package jimm.ui;

import DrawControls.*;
import DrawControls.icons.Icon;
import DrawControls.text.Par;
import DrawControls.text.Parser;
import java.util.*;
import jimm.*;
import jimm.comm.*;
import jimm.modules.traffic.*;
import jimm.ui.menu.*;
import jimm.ui.base.*;
import jimm.ui.timers.*;
import jimm.util.*;

/**
 *
 * @author vladimir
 */
public class TextListEx extends TextList implements SelectListener {

    private MenuModel menu;
    private TextListExCommands vlCommands;

    public TextListEx(String title) {
        super(title);
        setFontSet(GraphicsEx.chatFontSet);
    }

    public final void setUpdateListener(TextListExCommands vlCommands) {
        this.vlCommands = vlCommands;
    }

    protected void doKeyReaction(int keyCode, int actionCode, int type) {
        if ((null != vlCommands) && (KEY_PRESSED == type)) {
            switch (actionCode) {
                case NativeCanvas.NAVIKEY_LEFT:
                    vlCommands.onContentMove(this, -1);
                    return;

                case NativeCanvas.NAVIKEY_RIGHT:
                    vlCommands.onContentMove(this, +1);
                    return;
            }
        }
        super.doKeyReaction(keyCode, actionCode, type);
    }
    // #sijapp cond.if modules_TOUCH is "true"#

    protected void stylusXMoved(int fromX, int fromY, int toX, int toY) {
        if (getWidth() / 2 < Math.abs(fromX - toX)) {
            vlCommands.onContentMove(this, (fromX > toX) ? -1 : +1);
        }
    }
    // #sijapp cond.end#

    protected final void removeFirstText() {
        int size = getSize();
        if (0 < size) {
            int top = Math.max(0, getTopOffset() - getPar(0).getHeight());
            pars.removeElementAt(0);
            setCurrentItem(Math.max(0, getCurrItem() - 1));
            setTopByOffset(top);
            invalidate();
        }
    }

    // Returns text in current selection
    protected final String getCurrText() {
        Par par = getPar(getCurrItem());
        return (null == par) ? null : par.getText();
    }

    private String getAllText() {
        StringBuffer result = new StringBuffer();

        // Fills the lines
        int size = getSize();
        for (int i = 0; i < size; ++i) {
            String text = getPar(i).getText();
            if (null != text) {
                result.append(text).append("\n");
            }
        }
        String retval = result.toString().trim();
        return (0 == retval.length()) ? null : retval;
    }

    public void copy(boolean all) {
        String text = all ? getAllText() : getCurrText();
        if (null != text) {
            JimmUI.setClipBoardText(getCaption(), text);
        }
    }

    protected MenuModel getMenu() {
        return menu;
    }

    public final void setMenu(MenuModel menu, int defCode) {
        this.menu = menu;
        setDefaultCode(defCode);
        updateSoftLabels();
        invalidate();
    }

    private void updateSoftLabels() {
        MenuModel model = getMenu();
        String more = null;
        String ok = null;
        if (null != model) {
            more = "menu";
            ok = model.getItemText(defaultCode);
        }
        setSoftBarLabels(more, ok, "back", false);
    }

    protected void restoring() {
        updateSoftLabels();
    }

    public final int getCurrTextIndex() {
        int parIndex = getCurrItem();
        if ((getSize() <= parIndex) || (parIndex < 0)) {
            return -1;
        }
        return getPar(parIndex).index;
    }

    protected void itemSelected() {
        if (MENU_OPENURL == defaultCode) {
            if (-1 != getCurrTextIndex()) {
                Jimm.openUrl(getCurrText());
            }
        } else {
            MenuModel m = getMenu();
            if ((-1 != defaultCode) && (null != m)) {
                m.exec(null, defaultCode);
            }
        }
    }

    public final void setInfoMessage(String text) {
        Parser par = createParser(-1);
        par.addText(text, CanvasEx.THEME_TEXT, FONT_STYLE_PLAIN);
        addPar(par);
    }
    //////////////////////////////////////////////////////////////////////////////
    //                                                                          //
    // About                                                                    //
    //                                                                          //
    //////////////////////////////////////////////////////////////////////////////
    // String for recent version
    private static final int MENU_UPDATE = 0;
    private static final int MENU_LAST = 1;
    private static final int MENU_OPENURL = -2;

    public void initAbout() {
        System.gc();
        System.gc();
        long freeMem = Runtime.getRuntime().freeMemory() / 1024;

        lock();
        clear();

        setFontSet(GraphicsEx.chatFontSet);

        setCaption(JLocale.getString("about"));

        final String commaAndSpace = ", ";

        String[] params = Util.explode(JLocale.getString("about_info"), '\n');
        addPlainText("\n " + params[0] + "\n\n", THEME_TEXT);
        addPlainText("" + params[2] + "\n", THEME_TEXT);
        for (int i = 3; i < params.length; ++i) {
            int end = params[i].indexOf(':');
            if (-1 == end) {
                addPlainText("\n", THEME_TEXT);
            } else {
                String key = params[i].substring(0, end);
                String value = params[i].substring(end + 1).trim();
                if (value.startsWith("http://")) {
                    addUrl(key, value, uiBigTextIndex++);
                } else {
                    addAboutParam(key, value);
                }
            }
        }

        String partner = Jimm.getAppProperty("Jimm-Partner", null);
        if (!StringConvertor.isEmpty(partner)) {
            addUrl("Partner", StringConvertor.cut(partner, 50), uiBigTextIndex++);
        }
//        addPlainText("\n", THEME_TEXT); //changed

        String midpInfo = Jimm.microeditionPlatform;
        if (null != Jimm.microeditionProfiles) {
            midpInfo += commaAndSpace + Jimm.microeditionProfiles;
        }
        String locale = System.getProperty("microedition.locale");
        if (null != locale) {
            midpInfo += commaAndSpace + locale;
        }
        addAboutParam("midp_info", midpInfo);

        addPlainText("\n", THEME_TEXT);                            //add
        addBoldText(JLocale.getString("heap"), THEME_TEXT);        //add
        addPlainText("\n", THEME_TEXT);                            //add
        addAboutParam("free_heap", freeMem + JLocale.getString("kb"));
        addAboutParam("total_mem", (Runtime.getRuntime().totalMemory() / 1024)
                + JLocale.getString("kb"));

        // #sijapp cond.if modules_UPDATES is "true" # //updates modules
        if (null != Jimm.lastDate) {
            addAboutParam("latest_ver", Jimm.lastDate);
        }
        // #sijapp cond.end# //updates modules

        // #sijapp cond.if modules_TRAFFIC is "true" #
        addPlainText("\n", THEME_TEXT);                            //add
        addBoldText(JLocale.getString("traffic_lng"), THEME_TEXT); //add
        addPlainText("\n", THEME_TEXT);                            //add
        Traffic t = Traffic.getInstance();
        // Traffic for a session
        int sessionIn  = t.getSessionInTraffic();
        int sessionOut = t.getSessionOutTraffic();
        int session    = sessionIn + sessionOut;
        int sessionCost = t.generateCostSum(sessionIn, sessionOut, false);
        addTrafficSection(JLocale.getString("session"),
                session,
                sessionCost);

        // Traffic since date
        int totalIn  = t.getAllInTraffic();
        int totalOut = t.getAllOutTraffic();
        int total    = totalIn + totalOut;
        int totalCost = t.generateCostSum(totalIn, totalOut, true);
        addTrafficSection(JLocale.getString("traffic_since") + " "
                + t.getTrafficString(),
                total,
                totalCost);       
        // #sijapp cond.end #
        addPlainText("\n", THEME_TEXT);                                                  //add
        addBoldText(JLocale.getString("modules"), THEME_TEXT);                           //add
        addPlainText("\n", THEME_TEXT);                                                  //add
        addPlainText("###MODULES###" + "\n", THEME_TEXT);                                //add
        addPlainText("\n", THEME_TEXT);                                                  //add
        addBoldText(JLocale.getString("site"), THEME_TEXT);                              //add
        addPlainText("\n", THEME_TEXT);                                                  //add
        addUrl("base_site", "http://www.jimm.org/", uiBigTextIndex++);                   //add
        addUrl("off_site", "http://jimm.net.ru/", uiBigTextIndex++);                     //add
        addUrl("mod_site", "http://code.google.com/p/jimm-fork-van/", uiBigTextIndex++); //add
        addPlainText("\n", THEME_TEXT);                                                  //add

        MenuModel m = new MenuModel();
        // #sijapp cond.if modules_UPDATES is "true" # //updates modules
        m.addItem("get_last_version", MENU_LAST);
        // #sijapp cond.end# //updates modules
        m.addItem("update", MENU_UPDATE);
        m.setActionListener(this);
        setMenu(m, MENU_OPENURL);
        unlock();
    }

    // #sijapp cond.if modules_TRAFFIC is "true" #
    private void addTrafficSection(String title, int total, int cost) {
        addPlainText(title, THEME_TEXT);
        addPlainText(": ", THEME_TEXT);
        addPlainText(StringConvertor.bytesToSizeString(total, false), THEME_PARAM_VALUE);
        // The cost of the traffic
        if (0 < cost) {
            addPlainText(" (", THEME_TEXT);
            addPlainText(Traffic.costToString(cost), THEME_PARAM_VALUE);
            addPlainText(")", THEME_TEXT);
        }
        addPlainText("\n", THEME_TEXT);
    }
    // #sijapp cond.end #
    private void addAboutParam(String langStr, String str) {
        addPlainText(JLocale.getString(langStr) + ": ", THEME_TEXT);
        addPlainText(str, THEME_PARAM_VALUE);
        addPlainText("\n", THEME_TEXT);
    }

    private void addUrl(String langStr, String url, int id) {
        addPlainText(JLocale.getString(langStr) + ":\n", THEME_TEXT);
        defaultParser = null;
        Parser line = createParser(id);
        line.addText(url, THEME_PARAM_VALUE, FONT_STYLE_PLAIN);
        addPar(line);
    }

    private void addPlainText(String text, byte colorType) {
        getDefaultParser().addText(text, colorType, FONT_STYLE_PLAIN);
        getDefaultParser().commit();
    }
    private void addBoldText(String text, byte colorType) {           //add
        getDefaultParser().addText(text, colorType, FONT_STYLE_BOLD); //add
        getDefaultParser().commit();                                  //add
    }                                                                 //add
    ///////////////////////////////////////////////////////////////////////////
    private Parser defaultParser;

    public final Parser getDefaultParser() {
        if ((0 < getSize()) && (null != defaultParser)) {
            Par last = getPar(getSize() - 1);
            if (-1 == last.index) {
                return defaultParser;
            }
        }
        defaultParser = createParser(-1);
        addPar(defaultParser);
        return defaultParser;
    }
    ///////////////////////////////////////////////////////////////////////////
    private static final int URL_MENU_GOTO = 10;
    private static final int URL_MENU_ADD = 11;
    private static final int URL_MENU_COPY = 12;

    public void gotoURL(String text) {
        Vector urls = Util.parseMessageForURL(text);
        if (null == urls) {
            return;
        }

        setCaption(JLocale.getString("goto_url"));
        MenuModel m = new MenuModel();
        m.addItem("select", URL_MENU_GOTO);
        // #sijapp cond.if protocols_JABBER is "true" #
        m.addItem("add_user", URL_MENU_ADD);
        // #sijapp cond.end #
        m.addItem("copy_text", URL_MENU_COPY);
        //menu.addItem("back",   MenuModel.BACK_COMMAND_CODE);
        m.setActionListener(this);
        setMenu(m, URL_MENU_GOTO);
        clear();
        for (int i = 0; i < urls.size(); ++i) {
            Parser url = createParser(i);
            url.addText((String) urls.elementAt(i), THEME_TEXT, FONT_STYLE_PLAIN);
            addPar(url);
        }
        Jimm.getJimm().getDisplay().closeMenus();
        show();
    }
    ///////////////////////////////////////////////////////////////////////////
    private String header = null;
    protected int uiBigTextIndex = 0;

    public void setHeader(String header) {
        this.header = header;
    }

    private void addHeader() {
        if (null != header) {
            Parser line = createParser(-1);
            line.addText(JLocale.getString(header),
                    THEME_TEXT, FONT_STYLE_BOLD);
            addPar(line);
            header = null;
        }
    }

    public void addParam(String langStr, String str) {
        if (!StringConvertor.isEmpty(str)) {
            addHeader();
            int id = uiBigTextIndex++;
            Parser line = createParser(id);
            line.addText(JLocale.getString(langStr) + ": ",
                    THEME_TEXT, FONT_STYLE_PLAIN);
            line.addText(str, THEME_PARAM_VALUE, FONT_STYLE_PLAIN);
            addPar(line);
        }
    }

    public void addParamImage(String langStr, Icon img) {
        if (null != img) {
            addHeader();
            int id = uiBigTextIndex++;
            Parser line = createParser(id);
            if (!StringConvertor.isEmpty(langStr)) {
                line.addText(JLocale.getString(langStr) + ": ",
                        THEME_TEXT, FONT_STYLE_PLAIN);
            }
            line.addImage(img);
            addPar(line);
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    public void addItem(String str, int code, boolean active) {
        byte type = active ? FONT_STYLE_BOLD : FONT_STYLE_PLAIN;
        Parser item = createParser(code);
        item.useMinHeight();
        item.addText(str, THEME_TEXT, type);
        addPar(item);
    }

    ///////////////////////////////////////////////////////////////////////////
    public void clear() {
        uiBigTextIndex = 0;
        setHeader(null);
        super.clear();
    }

    ///////////////////////////////////////////////////////////////////////////
    public void select(Select select, MenuModel model, int cmd) {
        switch (cmd) {
            case MENU_UPDATE:
                // #sijapp cond.if modules_UPDATES is "true" # //updates modules
                GetVersion.updateProgram();
                // #sijapp cond.end# //updates modules
                // #sijapp cond.if modules_UPDATES isnot "true" #                                                //add to update
                Jimm.platformRequestAndExit("http://code.google.com/p/jimm-fork-van/downloads/list?q=featured"); //add to update
                // #sijapp cond.end#                                                                             //add to update
                break;

            // #sijapp cond.if modules_UPDATES is "true" # //updates modules
            case MENU_LAST:
                new GetVersion(GetVersion.TYPE_DATE).get();
                restore();
                break;
           // #sijapp cond.end# //updates modules

            case MenuModel.BACK_COMMAND_CODE:
                back();
                clear();
                break;

            case URL_MENU_GOTO:
                back();
                Jimm.openUrl(getCurrText());
                break;

            case URL_MENU_COPY:
                copy(false);
                restore();
                break;

            case URL_MENU_ADD:
                restore();
                Jimm.openUrl("xmpp:" + Util.getUrlWithoutProtocol(getCurrText()));
                break;
        }
    }
}
